const { User } = require('../model')
const jwt = require('../util/jwt')
const { jwtSecret } = require('../config/config.default')

// 用户登录
exports.login = async (req, res, next) => {
  try {
    // 1. 数据验证
    // 2. 生成 token
    const user = req.user.toJSON()
    const token = await jwt.sign({
      userId: user._id
    }, jwtSecret, {
      expiresIn: 60 * 60 * 24
    })

    // 3. 发送成功响应（包含 token 的用户信息）
    delete user.password
    res.status(200).json({
      ...user,
      token
    })
  } catch (err) {
    next(err)
  }
}

// 用户注册
exports.register = async (req, res, next) => {
  try {
    let user = new User(req.body.user)
    await user.save()

    user = user.toJSON()

    delete user.password

    res.status(201).json({
      user
    })
  } catch (err) {
    next(err)
  }
}

// 获取当前登录用户
exports.getCurrentUser = async (req, res, next) => {
  try {
    res.status(200).json({
      user: req.user
    })
  } catch (err) {
    next(err)
  }
}

// 更新当前登录用户
exports.updateCurrentUser = async (req, res, next) => {
  try {
    // 处理请求
    res.send('updateCurrentUser')
  } catch (err) {
    next(err)
  }
}

// 获取指定用户资料
exports.getUserProfile = async (req, res, next) => {
  try {
    // 处理请求
    res.send('getUserProfile')
  } catch (err) {
    next(err)
  }
}

// 关注用户
exports.followUser = async (req, res, next) => {
  try {
    // 处理请求
    res.send('followUser')
  } catch (err) {
    next(err)
  }
}

// 取消关注用户
exports.unfollowUser = async (req, res, next) => {
  try {
    // 处理请求
    res.send('unfollowUser')
  } catch (err) {
    next(err)
  }
}

// 查询所有用户
exports.userAll = async (req, res, next) => {
  try {
    const {
      limit = 20,
      offset = 0,
      author,
      createdTime
    } = req.query
    const filter = {}

    if (author) {
      const user = await User.findOne({
        username: author
      })
      filter.author = user ? user._id : null
    }
    if (createdTime) {
      const start = createdTime
      const dateTime = new Date(createdTime);
      const end = dateTime.setDate(dateTime.getDate() + 1)
      console.log(new Date(start), new Date(end))
      // const createdTimes = await User.findOne({
      //   createdAt: {"$gte":new Date(start), "$lte": new Date(end)}
      // })
      filter.createdAt = {"$gte":new Date(start), "$lte": new Date(end)}
    }

    const users = await User.find(filter)
      .skip(Number.parseInt(offset)) // 跳过多少条
      .limit(Number.parseInt(limit)) // 取多少条
      .sort({
        // -1 倒叙，1 升序
        createdAt: -1
      })

    // 统计 mongoose 中所有数据
    // const usersCount = await User.countDocuments()
    // 统计过滤后的数量
    const usersCount = await User.count(filter)

    res.status(200).json({
      users,
      usersCount
    })
  } catch (err) {
    next(err)
  }
}